package com.glink.gateway.filters;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 登录认证日志记录模块
 *
 * @author rencl, wg
 * @since 2022-06-02
 */

@Component
public class GenerateLogGatewayFilterFactory implements GlobalFilter {
    private final static Logger log = LoggerFactory.getLogger(GenerateLogGatewayFilterFactory.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String gatewayRoute = "{}";
        Map<String, Object> attributes = exchange.getAttributes();
        for (String k : attributes.keySet()) {
            if (k.contains("gatewayRoute")) {
                gatewayRoute = JSONObject.toJSONString(attributes.get(k));
                break;
            }
        }
        long s = System.currentTimeMillis();
        ServerHttpRequest request = exchange.getRequest();
        log.info("路由记录 ============================= start at: " + s);
        log.info("	uri: " + request.getURI());
        log.info("	queryParams: " + request.getQueryParams());
        log.info("	headers: " + request.getHeaders());
        log.info("	gatewayRoute: " + gatewayRoute);
        long e = System.currentTimeMillis();
        log.info("路由记录 ============================= end at: " + e + "  耗时(毫秒): " + (e - s));

        return chain.filter(exchange);
    }
}